﻿using AutoMapper;
using D.Medicalcare.Domain.Entities;
using D.Medicalcare.ErrorCode;
using D.Medicalcare.Infrastructure.Interfaces;
using D.Medicalcare.Read.API.Application.Command.MenuCommand;
using D.Medicalcare.Read.API.Dtos;
using MediatR;

namespace D.Medicalcare.Read.API.Application.Handler.MenuHandler
{
    /// <summary>
    /// 递归处理
    /// </summary>
    public class GetMenuListHandler : IRequestHandler<GetMenuListCommand, APIResult<List<MenuTreeDTO>>>
    {
        private readonly IBaseRepository<Menu> menuRep;
        private readonly IMapper mapper;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="menuRep">仓储</param>
        /// <param name="mapper">映射</param>
        public GetMenuListHandler(IBaseRepository<Menu> menuRep, IMapper mapper)
        {
            this.menuRep = menuRep;
            this.mapper = mapper;
        }
        /// <summary>
        /// 处理方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<List<MenuTreeDTO>>> Handle(GetMenuListCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<MenuTreeDTO>> result = new APIResult<List<MenuTreeDTO>>();
            result.Code = APIEnum.Success;
            result.Msg = "显示成功";
            result.Data = GetTree(0);
            return Task.FromResult(result);

        }
        /// <summary>
        /// 递归
        /// </summary>
        /// <param name="pid">父级Id</param>
        /// <returns></returns>
        public List<MenuTreeDTO> GetTree(int pid)
        {
            var m = menuRep.GetAll().Where(x => x.ParentId == pid && !x.IsDeleted).ToList();
            var a = new List<MenuTreeDTO>();
            foreach (var item in m)
            {
                var mm = new MenuTreeDTO();
                mm.Id = item.MenuId;
                mm.Label = item.MenuName;
                mm.MenuUrl = item.MenuUrl;
                mm.Children = GetTree(item.MenuId);
                a.Add(mm);
            }
            return a;

        }
    }
}
